package com.example.demo.controller.sys;

import com.example.demo.common.validator.util.R;
import com.example.demo.entity.sys.SysUserEntity;
import com.example.demo.param.LoginParam;
import com.example.demo.service.sys.SysCaptchaService;
import com.example.demo.service.sys.SysUserService;
import com.example.demo.service.sys.SysUserTokenService;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.*;
import sun.dc.pr.PRException;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * @ClassName SysLoginController
 * @Description: 登录
 * @Author liyunjiang
 * @Date 2020/5/13 22:02
 */
@RestController
public class SysLoginController extends AbstractController {

    @Resource
    SysCaptchaService sysCaptchaService;
    @Resource
    SysUserService sysUserService;
    @Resource
    SysUserTokenService sysUserTokenService;

    /**
     * 获取验证码
     * @param response
     * @param uuid
     */
    @GetMapping("captcha.jpg")
    public void captcha(HttpServletResponse response,String uuid) throws IOException, PRException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");
        //获取图片验证码
        BufferedImage image = sysCaptchaService.getCaptcha(uuid);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        IOUtils.closeQuietly(out);
    }

    /**
     * 登录
     * @param param
     * @return
     */
    @PostMapping("/sys/login")
    public Map<String,Object> login(@RequestBody LoginParam param){
        // 校验验证码
        boolean validate = sysCaptchaService.validate(param.getUuid(), param.getCaptcha());
        if (!validate){
            return R.error("验证码不正确");
        }
        SysUserEntity sysUserEntity = sysUserService.queryByUserName(param.getUsername());
        if (sysUserEntity == null || !sysUserEntity.getPassword().equals(new Sha256Hash(param.getPassword(),sysUserEntity.getSalt()).toHex())){
            return R.error("账号或密码不正确");
        }
        //账号锁定
        if(sysUserEntity.getStatus() == 0){
            return R.error("账号已被锁定,请联系管理员");
        }
        //生成token，并保存到数据库
        R r = sysUserTokenService.createToken(sysUserEntity.getUserId());
        return r;
    }
}
